<template>
  <div class="form-container">
    <el-row type="flex" justify="center">
      <el-form style="width:100%;" ref="form" :model="form" :rules="formRules" label-position="left" label-width="80px">
        <!-- 角色名称 -->
        <el-row type="flex" justify="center">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('role.name')" prop="name">
              <el-input v-model="form.name" :placeholder="$t('input')"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 权限 -->
        <el-row type="flex" justify="center">
          <!-- <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('role.permissions')" prop="title">
              <el-input v-model="form.permissions" :placeholder="$t('select')"/>
            </el-form-item>
          </el-col> -->
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('role.permissions')" prop="title">
            <el-tree :data="roleTree" 
              :props="defaultProps" 
              show-checkbox
              ref="permissionTree"
              node-key="permission_id" 
              @check-change="handleCheckChange">
            </el-tree>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 提交 -->
        <el-row type="flex" justify="center">
          <el-button :loading="submitLoading" type="primary" @click.native.prevent="onSubmit">{{$t('submit')}}</el-button>
        </el-row>
      </el-form>
    </el-row>
  </div>
</template>

<script>
export default {
  name: 'PermissionForm',
  data() {
    return {
      form: {
        name: '',
        permissions: [],
      },
      // form 校验规则
      formRules: {
        name: [{
            required: true,
            trigger: "blur",
            message: this.$t("fieldRequired")
        }]
      },
      // 组件中的loading遮罩层对象，调用openFullScreenLoading方法时赋值
      loading: null,
      submitLoading: false,
      // 角色数据的树列表数据
      roleTree: [],
      // 树组件的props
      defaultProps: {
        children: 'son',
        label: function(data, node) {
          return `${data.name}(${data.title})`
        },
        // 'node-key': 'permission_id'
      },
      // 编辑中的角色对象
      role: null,
      // url的角色id参数
      roleID: this.$route.query.roleID
    }
  },
  created: function() {
    this.init()
  },
  methods: {
    /**
     * 组件初始化方法
     */
    init() {
      this.initEditRole()
    },
    onSubmit() {
      this.$message('submit!')
      this.$refs.form.validate(valid => {
        if (valid) {
          this.addOrUpdateRole()
        }
      })
    },
    onCancel() {
      this.$message({
        message: 'cancel!',
        type: 'warning'
      })
    },
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);

      const permissionsSet = new Set(this.form.permissions)
      if (checked) {
        permissionsSet.add(data.permission_id)
      } else {
        permissionsSet.delete(data.permission_id)
      }
      this.form.permissions = Array.from(permissionsSet)
    },
    /**
     * 编辑角色初始化
     */
    initEditRole() {
      this.openFullScreenLoading()

      const promises = []
      if (this.roleID) {
        promises.push(this.getRoleDetailByID(this.roleID))
        promises.push(this.getAllPermissionList())
      } else {
        promises.push(this.getAllPermissionList())
      }
      Promise.all(promises).then(datas => {
        if (Array.isArray(datas)) {
          if (datas.length === 2) {
            this.processRoleData(datas[0])
            this.processPermissionListData(datas[1])
          } else if (datas.length === 1) {
            this.processPermissionListData(datas[0])
          }
        }

        this.closeFullScreenLoading()
      }).catch(error => {
        this.closeFullScreenLoading()

        console.error('init edit role has error:', error)
        this.$notify.error({
          title: this.$t('operationFailed'),
          message: this.$t('errorTips'),
        })
      }) 
    },
    /**调用api，提交或更新角色 */
    addOrUpdateRole() {
      this.submitLoading = true
      let promise
      
      if (this.roleID) {
        // 更新角色需要带id
        this.form.role_id = this.roleID
        promise = this.$store
          .dispatch('updateOneRole', this.form)
      } else {
        promise = this.$store
          .dispatch('addOneRole', this.form)
      }
      
      if (promise) {
        promise.then(data => {
          this.submitLoading = false;
          
          if (data && data['code'] === 0) {
            this.$notify({
              title: this.$t('operationSuccess'),
              message: data['msg'],
              type: 'success'
            })
          } else {
            this.$notify({
              title: this.$t('operationFailed'),
              message: data['msg'],
              type: 'warning'
            })
          }

          this.goToRoleManagement()
        }).catch((error) => {
          console.error('add or update role has error:', error)
          this.submitLoading = false;
          let msg = this.$t('errorTips')
          if (error && error['code'] !== 0) {
            msg = error['msg']
          }
          this.$notify.error({
            title: this.$t('operationFailed'),
            message: msg,
          })
        })
      }
    },
    /**
     * 调用api，获取所有权限
     */
    getAllPermissionList() {
      return this.$store
        .dispatch('getRolePermissionList')
    },
    /**
     * 处理权限数据
     */
    processPermissionListData(data) {
      if (data && data['code'] === 0) {
        const permissionDatas = data['data']

        if (Array.isArray(permissionDatas) && permissionDatas.length > 0) {
          this.roleTree = permissionDatas
        }
      } else {
        this.$notify({
          title: this.$t('operationFailed'),
          message: data['msg'],
          type: 'warning'
        })
      }
    },
    /**
     * 选中已选择的权限
     */
    setUpCheckedTreeNode(keys) {
      this.$refs.permissionTree.setCheckedKeys(keys)
    },
    /**
     * 调用api，获取角色详情数据
     */
    getRoleDetailByID(id) {
      return this.$store.dispatch('getRoleByID', { id })
    },
    /**
     * 处理role数据
     */
    processRoleData(data) {
      if (data && data['code'] === 0) {
        const roleData = data['data']

        this.role = roleData

        this.form.name = roleData.name
        this.form.permissions = roleData.permissions.map(item => item.permission_id)

        this.setUpCheckedTreeNode(this.form.permissions)
      } else {
        this.$notify({
          title: this.$t('operationFailed'),
          message: data['msg'],
          type: 'warning'
        })
      }
    },
    /**
     * 跳转到角色管理页面
     */
    goToRoleManagement() {
      this.$router.push({ path: '/role' })
    },
    /**
     * 显示loading遮罩层
     */
    openFullScreenLoading() {
      this.loading = this.$loading({
        lock: true,
        text: this.$t('loading') + '...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    /**
     * 关闭loading遮罩层
     */
    closeFullScreenLoading() {
      if (this.loading) {
        this.loading.close()
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "@/styles/variables.scss";
@import "../../styles/form-public";
</style>

